package org.netty.push.client;

import java.net.ConnectException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.netty.push.core.proto.ConnectRequestMsg;
import org.netty.push.core.proto.PingRequestMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

public class PushClient {
	Logger logger = LoggerFactory.getLogger(PushClient.class);
	/**
	 * 工作线程池
	 */
	private EventLoopGroup workGroup = new NioEventLoopGroup(4);
	private final String inetHost = "127.0.0.1";
	private final int inetPort = 8088;
	
	private ChannelFuture ch;
	private Channel channel;

	public PushClient() {

	}

	public boolean connected() {
		try {
		     Bootstrap bootstrap = new Bootstrap();
			// 2、工作线程
			bootstrap.group(workGroup);
			// 3、设置IO类型
			bootstrap.channel(NioSocketChannel.class);
			// 4、设置系统参数
			bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
			// 5设置日志handler
			bootstrap.handler(new LoggingHandler());
			// 6、初始化管道
			bootstrap.handler(new ClientChannelInitializer());
			ch = bootstrap.connect(inetHost, inetPort).sync();
			
			channel = ch.channel();
			
			logger.info("\n client startup .................");
			testConnected();
			doLogin();
			return true;
		} catch (Exception e) {
			logger.error("client start fail ,will to reconnected ...." + e.getMessage(), e);
			
			if(e instanceof ConnectException) {
				workGroup.schedule(new Runnable() {
					
					@Override
					public void run() {
						connected();	
					}
				}, 10, TimeUnit.SECONDS);
			}
		}
		return true;
	}

	public static void main(String[] args) {
		PushClient pushClient = new PushClient();
		pushClient.connected();

	}
	
	public boolean testConnected() {
		PingRequestMsg data = new PingRequestMsg();
		data.setId(UUID.randomUUID().toString());
		channel.writeAndFlush(data);
		return true;
	}
	
	public void doLogin() {
		ConnectRequestMsg data = new ConnectRequestMsg();
		data.setId(UUID.randomUUID().toString());
		data.setAppId("");
		data.setAppKey("");
		data.setKeySecret("");
		
		channel.writeAndFlush(data);
	}
}
